package org.huangrui.juc.source.cas;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 题目：实现一个自旋锁,复习CAS思想
 * 自旋锁好处：循环比较获取没有类似wait的阻塞。
 * <p>
 * 通过CAS操作完成自旋锁，A线程先进来调用myLock方法自己持有锁5秒钟，B随后进来后发现
 * 当前有线程持有锁，所以只能通过自旋等待，直到A释放锁后B随后抢到。
 *
 * @Author hr
 * @Create 2024-04-04 16:25
 */
public class T03_SpinLock {
    AtomicReference<Thread> atomicReference = new AtomicReference<Thread>();

    public void lock() {
        System.out.println(Thread.currentThread().getName() + "\t -----come in");
        Thread thread = Thread.currentThread();
        while (!atomicReference.compareAndSet(null, thread)) {
        }
    }

    public void unlock() {
        System.out.println(Thread.currentThread().getName() + "\t -----task over,unLock");
        atomicReference.compareAndSet(Thread.currentThread(), null);
    }

    public static void main(String[] args) {
        T03_SpinLock spinLock = new T03_SpinLock();
        
        new Thread(() ->{
           spinLock.lock();
           //暂停2秒钟
           try { TimeUnit.SECONDS.sleep(2);} catch (InterruptedException e) {e.printStackTrace();}
           spinLock.unlock();
        },"t1").start();
        
        //暂停1秒钟
        try { TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {e.printStackTrace();}
        new Thread(() ->{
           spinLock.lock();
           
           spinLock.unlock();
        },"t2").start();
    }
}
